/*VaWVqaRPOcVLGQLUZRykSxN43lbEnxQvSuDfiMhf4NYKgvGSAU5ZxOpOA4snWHov*/
/**
 * 待生成固定资产卡片列表页
 * @author zhangypm
 * @since ncc1.0 2018年6月29日
 */

import React, { Component } from 'react';
import { createPage, ajax, base, toast } from 'nc-lightapp-front';
import constants from './constants';
import { dataSource } from '../source/constants';
import { buttonClick, initTemplate, afterEvent, beforeEvent, lockrequest, bodyBatchChangeEvent } from './events';
import { depmethodUtils } from '../../facardbase/utils';
let { checkDepmethod } = depmethodUtils;

import ampub from 'ampub';
import fa from 'fa';

const {
	components: { LoginContext: { getContext } },
	utils: {
		listUtils: { getTitleName, creatListSocket },
		cardUtils: { createCardTitleArea },
		msgUtils: { showErrorMessageByRes }
	}
} = ampub;
const { fa_utils: { Relogin: { closeWindowWhenRelogin } } } = fa;
const {
	LIST_BTNS,
	PAGE_CODE,
	URL,
	UISTATE,
	FIELDS,
	BILL_SOURCE_TYPES,
	AREA: { LIST: { GRID_AREA: tableId } }
} = constants; //表格区
const { NCAffix } = base;

class List extends Component {
	constructor(props) {
		super(props);

		props.use.cardTable(tableId);

		/*assetDataMap: {
                row_index: [assetvo, assetvo,...]
        },*/
		this.assetDataMap = {};

		this.usufructDataMap = [];

		//CardVO 的属性
		this.cardVoAttributes = '';
		//业务字段
		this.busiFields = [];

		//使用部门的缓存，缓存所有行数据, 这是为了便于处理 单使用部门，多使用部门的切换及重复编辑问题
		this.usedeptCache = {};

		this.templateid = '';

		//上游单据表头主键被加锁的集合
		this.sourceBillHeadPksLocked = new Set();

		//固定资产参数
		this.FAParamMap = {}; //以 pk_org 进行区分

		this.fa83param = false; //--支持多成本中心分摊	否（默认值）(集团级数据)

		this.depmethods = []; //所有的折旧方法

		this.currentStatus = UISTATE.EDIT;

		this.doInit.bind(this);
		this.syncDataForCommit.bind(this);
		this.initSyncAccbook.bind(this);
		this.getDataBack.bind(this);
		this.setFAParamVOs.bind(this);
	}

	componentDidMount() {
		closeWindowWhenRelogin(this);

		initTemplate.call(this, this.props);
		const that = this;

		this.doInit().then(() => {
			that.getData();
		});
	}

	componentWillMount() {
		// 监听浏览器关闭
		window.onbeforeunload = () => {
			if (!!window.ActiveXObject || 'ActiveXObject' in window) {
				//IE11浏览器（同步解锁）
				lockrequest.call(this, [ ...this.sourceBillHeadPksLocked ], 'unlock', false);
			} else {
				//其它浏览器（异步解锁）
				lockrequest.call(this, [ ...this.sourceBillHeadPksLocked ], 'unlock', true);
			}
			//浏览器回退键
			if (window.history && window.history.pushState) {
				window.onpopstate = () => {
					lockrequest.call(this, [ ...this.sourceBillHeadPksLocked ], 'unlock', false);
				};
			}
		};
	}

	// 移除事件
	componentWillUnmount() {
		window.onbeforeunload = null;
	}

	//初始化
	doInit() {
		const that = this;
		const promise = new Promise((resolve, reject) => {
			ajax({
				url: '/nccloud/fa/assettransfer/init.do',
				data: {},
				success: (res) => {
					let { success, data } = res;
					if (success) {
						that.cardVoAttributes = data.cardVoAttributes;
						that.fa83param = data.FA83;
						that.depmethods = data.depmethods;

						//业务字段
						let busiFields = new Set(data.cardVoAttributes);
						FIELDS.BUSINESS_FIELD.map((f) => {
							busiFields.add(f);
						});
						that.busiFields = [ ...busiFields ];

						resolve(data.cardVoAttributes);
					} else {
						reject(data);
					}
				},
				error: (err) => {
					showErrorMessageByRes(that.props, err);
					reject(err);
				}
			});
		});
		return promise;
	}

	getData() {
		const that = this;

		//从 缓存 中获取上游存储的数据
		let sourceBill = getContext.call(this, 'multiSource_for_facard', dataSource);
		if (sourceBill && sourceBill.length) {
			sourceBill = JSON.parse(sourceBill);

			sourceBill.map((sb) => {
				if (sb.sourceBillType == BILL_SOURCE_TYPES.contract_src) {
					// 合同表体主键
					const pks = sb.sourceBodyPks;
					for (let pk of pks) {
						this.sourceBillHeadPksLocked.add(pk);
					}
				} else {
					this.sourceBillHeadPksLocked.add(sb.sourceHeadPk);
				}
			});

			this.sourceBill = sourceBill;

			ajax({
				url: URL.transvo,
				data: {
					pageCode: PAGE_CODE.LIST,
					templateid: this.templateid,
					transferInfos: sourceBill
				},
				success: (res) => {
					let { success, data } = res;
					if (success) {
						if (data && data.length) {
							this.getDataBack(data);
						}
					}
				},
				error: (res) => {
					showErrorMessageByRes(that.props, res);
				}
			});
		}
	}

	getDataBack(data) {
		const { props: { cardTable } } = this;
		const tableData = [];

		// data is array
		for (let i = 0; i < data.length; i++) {
			const assetvos = data[i]['model'].rows;
			for (let row of assetvos) {
				//折旧方法 是否停用 判断处理，如果折旧方法已经停用，则清空该字段
				row['values']['pk_depmethod'] = checkDepmethod(row['values']['pk_depmethod'], this.depmethods);
			}

			//得到主账簿数据
			const mainAccbookData = this.getMainAccbookData(assetvos);
			if (mainAccbookData) {
				tableData.push(mainAccbookData);
			} else {
				//没有主账簿数据的，说明没有资产类别
				tableData.push(assetvos[0]);
			}
			this.assetDataMap[i] = assetvos;
		}
		let paramVOs = JSON.parse(data[0].userjson);
		this.setFAParamVOs(paramVOs);
		if (data[0].combinationUsufructAssetDatas && data[0].combinationUsufructAssetDatas.length > 0) {
			this.combinationUsufructAssetDatas = data[0].combinationUsufructAssetDatas;
		} else {
			this.combinationUsufructAssetDatas = [];
		}
		//设置表格数据
		cardTable.setTableData(tableId, { rows: tableData }, () => {});

		// 控制合同单据原币币种的编辑性
		let editableRowid = tableData
			.filter((row) => {
				let { values: { bill_source: { value: bill_source } } } = row;
				// 此行是合同的单据
				return bill_source == BILL_SOURCE_TYPES.contract_src;
			})
			.map((row) => row.rowid);
		cardTable.setEditableByRowId(tableId, editableRowid, [ 'pk_currency' ], false);
	}

	setFAParamVOs(paramVOs) {
		let FAParamMap = {};
		for (let paramVO of paramVOs) {
			FAParamMap[paramVO.pk_org] = paramVO;
		}
		this.FAParamMap = FAParamMap;
	}

	getMainAccbookData(assetvos) {
		let mainAccbookData = undefined;
		if (assetvos != undefined) {
			assetvos.some((assetvo) => {
				if (assetvo.values.business_flag.value) {
					mainAccbookData = assetvo;
					return true;
				}
			});
		}
		return mainAccbookData;
	}

	getDataByAccbook(assetvos, accbook) {
		let accbookData = undefined;
		if (assetvos != undefined) {
			assetvos.some((assetvo) => {
				if (assetvo.values.pk_accbook.value == accbook) {
					accbookData = assetvo;
					return true;
				}
			});
		}
		return accbookData;
	}

	//获取业务账簿
	getMainAccbook(assetvos) {
		let business_accbook = '';
		if (assetvos != undefined) {
			assetvos.some((assetvo) => {
				if (assetvo.values.business_flag.value) {
					business_accbook = assetvo.values.pk_accbook.value;
					return true;
				}
			});
		}
		return business_accbook;
	}

	/**
     * 首次录入值并且是财务字段，同步所有账簿
     * @param {变动字段} field 
     * @param {当前表头} assetvos 
     */
	initSyncAccbook(field, assetvos) {
		if (!FIELDS.ACCOUNT_FIELD.includes(field)) {
			return;
		}

		let mainaccbookData = this.getMainAccbookData(assetvos);
		if (!mainaccbookData) {
			//如果不存在主账簿数据（还未设置资产类别时没有主账簿数据），直接返回
			return;
		}

		let otherAccbookDatas = assetvos.filter((assetvo) => {
			return assetvo.values.pk_accbook.value != mainaccbookData.values.pk_accbook.value;
		});

		if (otherAccbookDatas.length > 0) {
			for (let otherAccbookData of otherAccbookDatas) {
				if (!otherAccbookData.values[field].value) {
					otherAccbookData.values[field] = mainaccbookData.values[field];
				}
			}
		}
	}

	//提交数据前同步数据： 同步业务字段的数据（与账簿无关的数据）
	//单个卡片多个账簿之间数据的同步
	syncDataForCommit(assetvos) {
		let mainaccbookData = this.getMainAccbookData(assetvos);
		if (!mainaccbookData) {
			//如果不存在主账簿数据（还未设置资产类别时没有主账簿数据），直接返回
			return;
		}
		let otherAccbookDatas = assetvos.filter((assetvo) => {
			return assetvo.values.pk_accbook.value != mainaccbookData.values.pk_accbook.value;
		});

		if (otherAccbookDatas.length > 0) {
			for (let otherAccbookData of otherAccbookDatas) {
				//同步 BUSINESS_FIELD 数据到各个 asset
				for (let businessField of this.busiFields) {
					otherAccbookData.values[businessField] = mainaccbookData.values[businessField];
				}
			}
		}
	}

	/* 重点关注 */
	//跳转到来源单据页
	backToSource() {
		buttonClick.call(this, this.props, LIST_BTNS.HEAD.EXIT_TRANFER);
	}

	render() {
		let { cardTable, button, modal } = this.props;
		let { createCardTable } = cardTable;
		let { createModal } = modal;
		let { createButtonApp, createButton } = button;

		return (
			<div className="nc-bill-list">
				<NCAffix>
					<div className="nc-bill-header-area">
						<div className="header-title-search-area">
							{/*编辑卡片列表*/}
							{createCardTitleArea.call(this, this.props, {
								title: getTitleName(this.props),
								backBtnClick: this.backToSource
							})}
						</div>
						<div className="header-button-area">
							{createButtonApp({
								area: 'card_head',
								buttonLimit: 10,
								onButtonClick: buttonClick.bind(this)
							})}
						</div>
					</div>
				</NCAffix>

				<div className="nc-bill-table-area">
					{createCardTable(tableId, {
						onBeforeEvent: beforeEvent.bind(this),
						onAfterEvent: afterEvent.bind(this),
						showCheck: true,
						showIndex: true,
						otherAreaHeight: 50,
						onBatchChange: bodyBatchChangeEvent.bind(this),
						adaptionHeight: true,
						high_selectable: {
							enable: true
						},
						//如果有批选后事件，在此处理
						onBatchSelected: (...params) => {}
					})}
				</div>
				{/* 预警提示框 */}
				{createModal('budgetControl', { color: 'warning' })}
				{/* 创建 socket 链接 */}
				{creatListSocket(this.props, {
					tableAreaCode: tableId, //表格区域编码
					billpkname: 'pk_card', //表格主键
					billtype: 'H1', //单据类型,用于查询追溯
					tableType: 'cardTable' //表格类型，可以为 cardTable, editTable,insertTable
				})}
			</div>
		);
	}
}

List = createPage({
	billinfo: {
		billtype: 'grid',
		pagecode: PAGE_CODE.LIST,
		bodycode: tableId,
		tabletype: 'cardTable'
	}
})(List);
export default List;

/*VaWVqaRPOcVLGQLUZRykSxN43lbEnxQvSuDfiMhf4NYKgvGSAU5ZxOpOA4snWHov*/